compiler = require('../compiler/compiler');

http = require('http');
fs = require('fs');
html = fs.readFileSync('index.html', 'utf-8');

http.createServer(function (request, response) {
	if( request.method == 'POST' && require('url').parse(request.url).pathname == '/update/' ) {
        var body = '';
        request.on('data', function (data) {
            body += data;
            if (body.length > 1e6) {
                request.connection.destroy();
            }
        });
        request.on('end', function () {
            var POST = require('querystring').parse(body);

			var util  = require('util'),
			    spawn = require('child_process').spawn,
			    batchjs = spawn('batchjs', ['-cs', POST.inp]);

			var output = "";
			batchjs.stdout.on('data', function (data) {
			  	output = output + data;
			});
	
			batchjs.stderr.on('data', function (data) {
			  	output = output + data;
			});

			batchjs.on('exit', function (code) {
			  	response.writeHead(200, {'Content-type': 'text/plain'});
				response.end(output);
			});
        });
	}
	else {
		response.writeHead(200, {'Content-Type': 'text/html'});
		response.end(html);
	}

}).listen(8124);

console.log('Server running at http://nodejs:8124');